<?php
/**
    flattrpost v0.3
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    flattrpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    flickrpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with flattrpost.  If not, see <http://www.gnu.org/licenses/>. 
**/

#error_reporting(E_ALL);

$TABLE_FLATTRPOST_CFG = $pixelpost_db_prefix . "flattrpost_cfg";
$SITE_URL = $cfgrow['siteurl'];
$FLATTR_BUTTON_NORMAL = "addons/_flattrpost/button-static-55x62.png";
$FLATTR_BUTTON_COMPACT = "addons/_flattrpost/button-compact-static-110x20.png";
$FLATTR_LANGS = array(
    'sq_AL' => 'Albanian', 
    'ar_DZ' => 'Arabic', 
    'be_BY' => 'Belarusian', 
    'bg_BG' => 'Bulgarian', 
    'ca_ES' => 'Catalan', 
    'zh_CN' => 'Chinese', 
    'hr_HR' => 'Croatian', 
    'cs_CZ' => 'Czech', 
    'da_DK' => 'Danish', 
    'nl_NL' => 'Dutch', 
    'en_GB' => 'English', 
    'et_EE' => 'Estonian', 
    'fi_FI' => 'Finnish', 
    'fr_FR' => 'French', 
    'de_DE' => 'German', 
    'el_GR' => 'Greek', 
    'iw_IL' => 'Hebrew', 
    'hi_IN' => 'Hindi', 
    'hu_HU' => 'Hungarian', 
    'is_IS' => 'Icelandic', 
    'in_ID' => 'Indonesian', 
    'ga_IE' => 'Irish', 
    'it_IT' => 'Italian', 
    'ja_JP' => 'Japanese', 
    'ko_KR' => 'Korean', 
    'lv_LV' => 'Latvian', 
    'lt_LT' => 'Lithuanian', 
    'mk_MK' => 'Macedonian', 
    'ms_MY' => 'Malay', 
    'mt_MT' => 'Maltese', 
    'no_NO' => 'Norwegian', 
    'pl_PL' => 'Polish', 
    'pt_PT' => 'Portuguese', 
    'ro_RO' => 'Romanian', 
    'ru_RU' => 'Russian', 
    'sr_RS' => 'Serbian', 
    'sk_SK' => 'Slovak', 
    'sl_SI' => 'Slovenian', 
    'es_ES' => 'Spanish', 
    'sv_SE' => 'Swedish', 
    'th_TH' => 'Thai', 
    'tr_TR' => 'Turkish', 
    'uk_UA' => 'Ukrainian', 
    'vi_VN' => 'Vietnamese'
);

$addon_name = "flattrpost<a name='flattrpost'></a>";
$addon_version = "0.3";
$addon_description = "Adds the new template tag &lt;FLATTR_BUTTON&gt; "
    . "to allow inserting image-specific <a href='https://flattr.com'>"
    . "flattr</a> buttons on the image pages. <br />";


// upgrade config table structure if necessary
// (this only happens on the admin/addons page for now - which means that new 
// versions of the template tag handling code must be able to work with old 
// config data)
if (isset($_GET['view']) and $_GET['view'] == 'addons') {
    $res = mysql_query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS "
        . "WHERE TABLE_NAME = '$TABLE_FLATTRPOST_CFG' and COLUMN_NAME = 'uid'")
        or die(mysql_error());
    if ($res != null and mysql_num_rows($res) == 1) {
        // don't do anything if table or column does not exist
        $coldata = mysql_fetch_array($res);
        if (isset($coldata["DATA_TYPE"]) 
            and in_array($coldata["DATA_TYPE"], array("int", "bigint", 
                                                      "smallint", "tinyint"), 
                                                      true)) {
            // change column data type to varchar (values will be converted)
            mysql_query("ALTER TABLE $TABLE_FLATTRPOST_CFG "
                . "MODIFY uid VARCHAR(255)") or die(mysql_error());
        }
    }
}

// store updated configuration if form on the admin/addons page was submitted
if (isset($_POST['flattrpost_do']) and $_POST['flattrpost_do'] == 'config') {
    $uid = trim($_POST['uid']);
    $add_tags = trim($_POST['add_tags']);
    $title_prefix = $_POST['title_prefix'];
    $desc_prefix = $_POST['desc_prefix'];
    $lang = $_POST['lang'];
    $noscript_url = trim($_POST['noscript_url']);
    $compact = isset($_POST['compact']) ? 1 : 0;
    $hide = isset($_POST['hide']) ? 1 : 0;
    $use_img_tags = isset($_POST['use_img_tags']) ? 1 : 0;
    mysql_query("UPDATE $TABLE_FLATTRPOST_CFG SET uid='{$uid}', lang='{$lang}', "
        . "compact='{$compact}', hide='{$hide}', noscript_url='{$noscript_url}', "
        . "use_img_tags='{$use_img_tags}', add_tags='{$add_tags}', "
        . "title_prefix='{$title_prefix}', desc_prefix='{$desc_prefix}'") 
        or die(mysql_error());
    $_SESSION['flattrpost_result'] = 'Configuration saved. ';
}

// addons page or template tag hit
if ((isset($image_id) and preg_match("<FLATTR_BUTTON>", $tpl)) or 
    (isset($_GET['view']) and $_GET['view'] == 'addons')) {
    
    // create config DB if it does not exist yet
    $res = mysql_query("SELECT * FROM $TABLE_FLATTRPOST_CFG LIMIT 1");
    if (!$res) {
        mysql_query("CREATE TABLE IF NOT EXISTS $TABLE_FLATTRPOST_CFG (
                     `uid` BIGINT, 
                     `compact` BOOL, 
                     `hide` BOOL, 
                     `use_img_tags` BOOL, 
                     `lang` VARCHAR(5), 
                     `noscript_url` VARCHAR(1000), 
                     `add_tags` VARCHAR(1000), 
                     `title_prefix` VARCHAR(1000), 
                     `desc_prefix` VARCHAR(1000)
                    )");
    }
    if (!$res or !mysql_num_rows($res) or mysql_num_rows($res) < 1) {
        // insert default config record
        $site_title = htmlspecialchars($cfgrow['sitetitle'], ENT_QUOTES);
    	mysql_query("INSERT INTO $TABLE_FLATTRPOST_CFG VALUES(0, 0, 0, 0, 'en_GB', " 
            . "'', 'flattrpost,photoblog,photo', 'Photo on {$site_title}: ', '')");
    }
    
    // populate config variables from config DB
    $result = mysql_query("SELECT * FROM $TABLE_FLATTRPOST_CFG LIMIT 1");
    $cfg = mysql_fetch_array($result);
    
    // build configuration form (shown on admnin/addons page)
    $compact_checked = $cfg['compact'] ? "checked='checked'" : '';
    $hide_checked = $cfg['hide'] ? "checked='checked'" : '';
    $use_img_tags_checked = $cfg['use_img_tags'] ? "checked='checked'" : '';
    $addon_description .= <<<EOT
    <p>Configuration: </p>
    <form action='{$SITE_URL}admin/index.php?view=addons#flattrpost' method='post' accept-charset='UTF-8'>
        <input type='hidden' name='flattrpost_do' value='config' />
        <table>
            <tr style='vertical-align:top;'>
                <td>
                    Flattr user ID: <br />
                    <span style="font-size:0.8em;">(as shown in the "Your user info" box on the flattr dashboard)</span>
                </td>
                <td><input type='text' size='40' name='uid' value='{$cfg['uid']}' /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Default tags for your flattr entries: <br />
                    <span style="font-size:0.8em;">(comma-separated)</span>
                </td>
                <td><input type='text' size='40' name='add_tags' value='{$cfg['add_tags']}' /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Append your photos' pixelpost tags: </td>
                <td><input type='checkbox' name='use_img_tags' {$use_img_tags_checked} /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Common title prefix: <br />
                    <span style="font-size:0.8em;">(can be left blank)</span>
                </td>
                <td><input type='text' size='40' name='title_prefix' value='{$cfg['title_prefix']}' /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Common description prefix: <br />
                    <span style="font-size:0.8em;">(can be left blank)</span>
                </td>
                <td><input type='text' size='40' name='desc_prefix' value='{$cfg['desc_prefix']}' /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Language of your entries: </td>
                <td>
                    <select name='lang'>
EOT;
    foreach ($FLATTR_LANGS as $key => $val) {
        $selected = ($cfg['lang'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$val}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Use compact flattr button: </td>
                <td><input type='checkbox' name='compact' {$compact_checked} /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Hide your photos from listings on flattr.com: </td>
                <td><input type='checkbox' name='hide' {$hide_checked} /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Generic flattr thing URL for &lt;noscript&gt; block: <br />
                    <span style="font-size:0.8em;">(if blank, no &lt;noscript&gt; block will be generated)</span>
                </td>
                <td><input type='text' size='40' name='noscript_url' value='{$cfg['noscript_url']}' /></td>
            </tr>
        </table>
        <input type='submit' value='Save' />
    </form>
EOT;
    if (isset($_SESSION['flattrpost_result'])) {
        $addon_description .= "<p><em>" . $_SESSION['flattrpost_result'] . '</em></p>';
        unset($_SESSION['flattrpost_result']);
    }
}

if (isset($image_id) and preg_match("<FLATTR_BUTTON>", $tpl)) {
    // retrieve tags for current image
    $flattr_tag = '';
    if ($cfg['use_img_tags']) {
    	$query = "SELECT DISTINCT tag "
               . "FROM {$pixelpost_db_prefix}tags "
               . "WHERE img_id = $image_id AND tag NOT LIKE '' ORDER BY tag ASC";
        $res = mysql_query($query);
    	while (list($tag) = mysql_fetch_row($res)) $flattr_tag .= $tag . ",";
    }
    // compile other arguments for flattr button code
    $flattr_tag .= $cfg['add_tags'];
    $flattr_tag = substr(trim($flattr_tag), 0, 255);
    $flattr_tag = preg_replace("/[^a-zA-Z0-9-_,]/", "_", $flattr_tag);
    $var_flattr_btn = $cfg['compact'] ? "button:compact;" : "";
    $flattr_url = $SITE_URL . "index.php?showimage=" . $image_id;
    $flattr_dsc = $cfg['desc_prefix'] . trim($image_notes_clean);
    $flattr_dsc = htmlentities($flattr_dsc, ENT_QUOTES, "UTF-8", false);
    $flattr_dsc = str_replace("\r", " ", str_replace("\n", " ", str_replace("\r\n", " ", $flattr_dsc)));
    $flattr_dsc = substr($flattr_dsc, 0, 1000);
    $flattr_dsc = str_pad($flattr_dsc, 5);  # desc needs to be at least 5 chars long
    $var_flattr_hide = $cfg['hide'] ? "hidden:1;" : "";
    $flattr_tle = $cfg['title_prefix'] . $image_title;
    $flattr_tle = substr($flattr_tle, 0, 100);
    $flattr_tle = str_pad($flattr_tle, 5);  # title needs to be at least 5 chars long
    // assemble flattr button code
    $flattr = "\n" . <<<EOT
        <!-- BEGIN FLATTR INITIALIZATION -->
        <script type="text/javascript">
        /* <![CDATA[ */
            (function() {
                var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];
                s.type = 'text/javascript';
                s.async = true;
                s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto';
                t.parentNode.insertBefore(s, t);
            })();
        /* ]]> */
        </script>
        <!-- END FLATTR INITIALIZATION -->
        <!-- BEGIN FLATTR BUTTON -->
        <a class="FlattrButton" style="display:none;"
            title="{$flattr_tle}"
            rev="flattr;uid:{$cfg['uid']};{$var_flattr_btn}{$var_flattr_hide}category:images;language:{$cfg['lang']};tags:{$flattr_tag}"
            href="{$flattr_url}">{$flattr_dsc}</a>
EOT;
    // append <noscript> block (if applicable)
    if ($cfg['noscript_url'] != "") {
        $button_url = $cfg['compact'] ? $FLATTR_BUTTON_COMPACT : $FLATTR_BUTTON_NORMAL;
        $flattr .= "\n" . <<<EOT
        <noscript>
            <a href="{$cfg['noscript_url']}" target="_blank">
                <img src="{$button_url}" alt="Flattr this" title="Flattr this" border="0" />
            </a>
        </noscript>
EOT;
    }
    $flattr .= "\n" . <<<EOT
        <!-- END FLATTR BUTTON -->
EOT;
    
    $tpl = str_replace("<FLATTR_BUTTON>", $flattr, $tpl);
}
?>